import React from 'react';
import ReactEcharts from 'echarts-for-react';
import echarts from 'echarts';
import classNames from 'classnames';

import geoJson from './yichang.json';
import { districtMap, districtMap2, geoCoordMap } from './geo';

import styles from './index.less';

class YcMapData extends React.Component {
  state = {
    width: (window.innerWidth - 980),
    height: (window.innerHeight - 136) * 0.9,
  };

  componentWillMount() {
    echarts.registerMap('yichang', geoJson);
  }

  componentDidMount() {
    window.addEventListener('resize', e => {
      this.resize((window.innerWidth - 980), (window.innerHeight - 136) * 0.9, e);
    });
  }

  resize = (width, height) => {
    this.setState({
      width,
      height,
    });
  };

  convertData = (data) => {
    const districtData = this.editDistrictData(data);
    const res = [];
    const scatterData = [
      { name: '西陵区', type: 'areaCenterCity', labelOffset: [0, 5] },
      { name: '伍家岗区', type: 'areaCenterCity', labelOffset: [20, 0] },
      { name: '猇亭区', type: 'areaCenterCity' },
      { name: '点军区', type: 'areaCenterCity', labelOffset: [-30, 50], symbolOffset: [-10, 0] },
      { name: '夷陵区', type: 'areaCenterCity', labelOffset: [10, -10] },
      { name: '宜都市', type: 'areaCenterCity', labelOffset: [0, 40] },
      { name: '当阳市', type: 'areaCenterCity' },
      { name: '枝江市', type: 'areaCenterCity' },
      { name: '长阳土家族自治县', type: 'areaCenterCity', labelOffset: [-80, 40] },
      { name: '五峰土家族自治县', type: 'areaCenterCity', labelOffset: [-80, 40] },
      { name: '秭归县', type: 'areaCenterCity', labelOffset: [-40, 40] },
      { name: '兴山县', type: 'areaCenterCity' },
      { name: '远安县', type: 'areaCenterCity' },
    ];
    scatterData.forEach(item => {
      const geoCoord = geoCoordMap[item.name];
      const itemDistrictData = districtData.filter(itemD => itemD.cantonName === item.name);
      if (geoCoord) {
        res.push({
          name: item.name,
          value: geoCoord.concat(item.name),
          type: item.type,
          symbolOffset: item.symbolOffset || 0,
          label: {
            normal: {
              formatter: itemDistrictData.length === 0 ? '{b}' : `{b}(${itemDistrictData[0].value})`,
              position: 'top',
              show: true,
              fontSize: 18,
              offset: item.labelOffset || 0,
            },
          },
        });
      }
    });

    return res;
  };

  mapClick = e => {
    const { onClick } = this.props;
    if (onClick) {
      onClick(e);
    }
  };

  editDistrictData = data => {
    const temp = [];
    Object.keys(districtMap2).forEach(district => {
      const dData = data.filter(item => districtMap2[district].includes(item.cantonName));
      if (dData.length === 0) {
        temp.push({
          cantonName: district,
          name: districtMap[district],
          value: 0,
        });
      } else if (dData.length === 1) {
        temp.push({
          ...dData[0],
          name: districtMap[district],
          value: dData.reduce((prv, next) => prv + next.count, 0),
        });
      } else {
        temp.push({
          ...dData.filter(item => item.cantonName === district)[0],
          child: dData,
          name: districtMap[district],
          value: dData.reduce((prv, next) => prv + next.count, 0),
        });
      }
    });
    return temp;
  };

  render() {
    const { width, height } = this.state;
    const { title, data = [], className = {}, tooltip = { title: '数量', unit: '' } } = this.props;

    return (
      <div className={classNames(className, styles.content)}>
        <ReactEcharts
          style={{ width, height }}
          onEvents={{
            click: this.mapClick,
          }}
          option={{
            title: {
              show: !!title,
              text: title,
              left: '5%',
              top: '5%',
              textStyle: {
                fontStyle: 'normal',
                fontWeight: 500,
                fontSize: '3.2vw',
                color: '#222',
                fontFamily:
                  'Helvetica, "PingFang SC", tahoma, arial, "helvetica neue", "hiragino sans gb", "microsoft yahei", sans-serif',
              },
            },
            tooltip: {
              trigger: 'item',
              transitionDuration: 0.2,
              show: false, // 不显示提示标签
              // formatter: '{a} {b} {c}', // 提示标签格式
              // 鼠标放地图的某一块，显示的提示框
              formatter(params) {
                const {
                  name,
                  data: { value, child },
                } = params;
                if (child) {
                  let bz = '';
                  child.forEach(item => {
                    bz += `<br />${item.cantonName}：${item.count}`;
                  });
                  return `${name}<br />${tooltip.title}：${value}${tooltip.unit}<br />备注：${bz}`;
                }
                return `${name}<br />${tooltip.title}：${value}${tooltip.unit}`;
              },
              backgroundColor: '#000', // 提示标签背景颜色
              textStyle: { color: '#fff' }, // 提示标签字体颜色
            },
            // 视觉映射组件
            visualMap: {
              type: 'piecewise',
              pieces: [
                {max: 0, label: '0'}, // 不指定 min，表示 min 为无限大（-Infinity）。
                {min: 1, max: 100, label: '1-100'},
                {min: 101, max: 300, label: '101-300'},
                {min: 301, max: 600, label: '301-600'},
                {min: 600, max: 1000, label: '601-1000'},
                {min: 1001, max: 1500, label: '1001-1500'},
                {min: 1501, max: 2000, label: '1501-2000'},
                {min: 2001, max: 2500, label: '2001-2500'},
                {min: 2501, max: 5000, label: '2501-5000'},
                {min: 5001, label: '5001以上' }, // 不指定 max，表示 max 为无限大（Infinity）。
              ],
              itemHeight: 20,
              itemWidth: 20,
              itemSymbol: 'rect',
              right: '5%',
              top: 'bottom',
              textStyle: {
                fontWeight: 'bold',
                fontSize: 18,
              },
              // min: 0,
              // max: 3000,
              orient: 'vertical',
              inRange: {
                color: [
                  '#ECF5FF',
                  '#D2E9FF',
                  '#C4E1FF',
                  '#ACD6FF',
                  '#97CBFF',
                  '#84C1FF',
                  '#66B3FF',
                  '#46A3FF',
                  '#2894FF',
                  '#0080FF',
                  '#0072E3',
                  '#0066CC',
                  '#005AB5',
                ],
              },
            },
            geo: {
              map: 'yichang',
              roam: false,
              zoom: 1.2,
              tooltip: {
                show: false, // 不显示提示标签
              },
              label: {
                normal: {
                  show: false, // 显示省份标签
                  textStyle: { color: '#c71585' }, // 省份标签字体颜色
                },
                emphasis: {
                  // 对应的鼠标悬浮效果
                  show: false,
                  textStyle: { color: '#800080' },
                },
              },
              itemStyle: {
                normal: {
                  borderWidth: 0.5, // 区域边框宽度
                  borderColor: '#000', // 区域边框颜色
                  areaColor: '#ffefd5', // 区域颜色
                  label: { show: false },
                },
                emphasis: {
                  show: false,
                  borderWidth: 0.5,
                  borderColor: '#4b0082',
                  areaColor: '#ffdead',
                },
              },
            },
            series: [
              {
                type: 'scatter',
                coordinateSystem: 'geo',
                data: this.convertData(data),
                symbol: 'pin',
                // symbolSize: 10,
                symbolRotate: 40,
                // symbolOffset: [100, 100],
                // label: {
                //   normal: {
                //     formatter: '{b}',
                //     position: 'top',
                //     show: true,
                //     fontSize: 18,
                //   },
                //   emphasis: {
                //     formatter: '{b}',
                //     position: 'top',
                //     show: true,
                //     fontSize: 24,
                //   },
                // },
                tooltip: {
                  show: false, // 不显示提示标签
                  // 显示提示的标签
                  formatter(name) {
                    return `Legend ${name}`;
                  }, // 提示标签格式
                  backgroundColor: '#fff', // 提示标签背景颜色
                  borderColor: '#ccc',
                  borderWidth: 5,
                  textStyle: { color: '#000' }, // 提示标签字体颜色
                },
                itemStyle: {
                  normal: {
                    color: '#FFF'
                  },
                },
              },
              {
                type: 'map',
                map: 'yichang',
                mapType: 'yichang',
                roam: false,
                zoom: 1.2,
                tooltip: {
                  show: true, // 不显示提示标签
                },
                label: {
                  normal: {
                    show: false,
                  },
                  emphasis: {
                    show: false,
                  },
                },
                itemStyle: {
                  normal: {
                    borderWidth: 0.5, // 区域边框宽度
                    borderColor: '#fff', // 区域边框颜色
                    label: { show: false },
                  },
                  emphasis: {
                    show: false,
                  },
                },
                // geoIndex: 0,
                // 鼠标放入地图显示提示框
                // tooltip: { show: true },
                data: this.editDistrictData(data),
              },
            ],
          }}
        />
      </div>
    );
  }
}

export default YcMapData;
